import React from 'react';
import {inject, observer} from "mobx-react";
import {toJS} from 'mobx';
import {withRouter, Route} from 'react-router-dom';
import loadjs from "loadjs";
import {TabBar, Icon, ActionSheet, Flex, Bubble, Modal, Checkbox, Tools} from 'weaver-mobile';
import * as CommonUtil from '../../../workflowForm/util/common';
import './style/index';
import jQuery from "jquery";
import * as pageTypes from "../../constants/OdocPageType";
import {initSignApprovalFloatDom,initSignApprovalButtonPosition,initSignApprovalTouchMove,signapprovalMoveForIos} from '../../util/CommonUtil';
import {RouteLayout} from 'weaver-mobile-page';
import DocumentHistoryVersion from './DocumentHistoryVersion';

const alert = Modal.alert;
const AgreeItem = Checkbox.AgreeItem;
const getLabel = Tools.getLabel;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}
const WfForm = window.WfForm;
const winWidth = jQuery(window).width();
@withRouter
@inject("odocSignApprovalStore", "odocComsStore")
@observer
class Index extends React.Component {

    componentWillMount() {
        const {odocSignApprovalStore} = this.props;
        let {setProperty} = odocSignApprovalStore;
        let {requestid, workflowid, nodeid,f_weaver_belongto_userid,f_weaver_belongto_usertype} = WfForm.getGlobalStore().commonParam;
        setProperty({
            requestid,
            workflowid,
            nodeid,
            f_weaver_belongto_userid,
            f_weaver_belongto_usertype
        })
    }

    componentDidMount() {
        let _that = this;
        let oDiv = document.getElementById('haoqian1');
        initSignApprovalFloatDom(oDiv, function (e) {
            oDiv.style.display = "none";
            initSignApprovalButtonPosition(document.getElementById('haoqian'));
            const {odocComsStore} = _that.props;
            const {onClose} = odocComsStore;
            window.historyRoute.go(-1);
            onClose && typeof onClose == "function" && onClose();
        },{signDeviceType:1});

        let {getQianPiDatas,doCheckSignApprovalFile} = this.props.odocSignApprovalStore;
        getQianPiDatas().then(data => {
            this.ayncLoadResource();
        });

        const {odocSignApprovalStore} = this.props;
        let {setProperty} = odocSignApprovalStore;

        jQuery(".wea-mobile-haoqian-button1").click(function () {
            setProperty({isShowQP: false});
        });
        jQuery("#ctx").click(function () {
            setProperty({isShowQP: false});
        });
        
    }


    componentWillUnmount() {
      let {getQianPiDatas,doCheckSignApprovalFile} = this.props.odocSignApprovalStore;
      doCheckSignApprovalFile(2);
    }

  /**
     *  异步加载契约锁js sdk资源
     */
    ayncLoadResource = () => {
        const {odocSignApprovalStore} = this.props;
        let {hasLoad, resourceFiles} = odocSignApprovalStore;
        if (!hasLoad) {
            const callbackFn = () => {
                this.loadHaoQianPage();
            }
            loadjs.isDefined('haoqianResources') ? loadjs.ready('haoqianResources', callbackFn) : loadjs(resourceFiles(), 'haoqianResources', callbackFn);
        } else {
            this.loadHaoQianPage();
        }

    }

    loadHaoQianPage = () => {
        const {odocSignApprovalStore} = this.props;
        let {sequenceId, token, userid, lastname, isSeal, setProperty, saveQianPiDatas,defaultSign,defaultWriteColor,defaultWriteSize} = odocSignApprovalStore;
        let WSMobileSignContext = window.WSMobileSignContext;
        let _that = this;
        let ctx = new WSMobileSignContext();
        // 初始化
        ctx.Init({
            el: '#ctx',
            token: token, // 替换此参数
            sequenceId: sequenceId, // 替换此参数
            callerId: userid+"",
            callerName: lastname
        });
        // 渲染
        ctx.Render({
            readonly: !isSeal,
            hiddenToolbar: true,
            defaultWriteColor:defaultWriteColor,
            defaultWriteSize:parseInt(defaultWriteSize),
            signboardLineColor:defaultWriteColor,
            signboardLineSize:parseInt(defaultWriteSize),
            defaultWordSize:parseInt(defaultWriteSize),
            defaultUnSaveToastText:getLabel('524496','暂无未保存的内容'),
        });
        // 保存成功的回调
        ctx.On('saveSucceed', function (buildname) {
            saveQianPiDatas(buildname);
        });
        // 自定义按钮的点击回调
        ctx.On('tbBtnClick', function (name) {
            if (name === 'myBuild') {
            }
            // name:用户自定义按钮的名称
        });
        // 因为涉及到接口请求，在请求失败，界面无法加载的时候会把结果回调给接入者。
        ctx.On('renderError', function (msg) {
            // msg的枚举待完善。。。
        });
        ctx.On('writeClose', () => {
          setProperty({qpSelected:false})
        });
        // 渲染成功
        ctx.On('renderSucceed', function (buildNo) {
            window.signApprovalCtx = ctx;
            _that.ctxRenderDoneEvent(ctx);
        });

    };

    //好签渲染完毕回调事件
    ctxRenderDoneEvent=(ctx)=>{
        const {odocSignApprovalStore} = this.props;
        let {sequenceId, token, userid, lastname, qpSelected, isSeal, setProperty, saveQianPiDatas,
          defaultSign,defaultWriteColor,defaultWriteSize} = odocSignApprovalStore;
        if((defaultSign && isSeal==true) || qpSelected==true){
            ctx.SimulateClickBtn("wsWriteBtn");//默认签批
            setProperty({defaultSign:false,qpSelected:true});
        }
        setProperty({ctx: ctx, hasLoad: true});

        WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, function (callback) {
            window.signApprovalCtx.CloseWrite();
            if (window.signApprovalCtx && window.signApprovalCtx.CheckoutHasUnsaveData()) {
                window.signApprovalCtx.SimulateClickBtn("wsSaveBtn");
                setTimeout(function () {
                    callback();
                }, 1000)
            } else {
                callback();
            }
        });

        WfForm.registerCheckEvent(WfForm.OPER_REJECT, function (callback) {
            window.signApprovalCtx.CloseWrite();
            if (window.signApprovalCtx && window.signApprovalCtx.CheckoutHasUnsaveData()) {
                window.signApprovalCtx.SimulateClickBtn("wsSaveBtn");
                setTimeout(function () {
                    callback();
                }, 1000)
            } else {
                callback();
            }
        });
    }

    showActionSheet = () => {
        let {odocSignApprovalStore, history} = this.props;
        let {btns, ctx} = odocSignApprovalStore;
        let BUTTONS = toJS(btns).filter((item, index) => index >= 4);
        BUTTONS.map(item => {
            if(item.key=="wsImageBtn"){
              item.content = <div className={"disabledfastclick"}>{item.name}</div>;
            }else {
              item.content = item.name;
            }
            item.onClick = () => {this.doRightMenuClick(item.key);}
        });
        BUTTONS = [
            ...BUTTONS,
            {
                content: getLabel('31129', '取消'),
                onClick: () => {
                },
            },
        ];
        ActionSheet.showActionSheetWithOptions({
                options: BUTTONS,
                cancelButtonIndex: BUTTONS.length - 1,
                maskClosable: true,
                'data-seed': 'logId',
                wrapProps,
            },
            (buttonIndex) => {
                // console.log(buttonIndex)
            }
        );
    };

    doIsSaveTip = (callback) => {
        let {odocSignApprovalStore} = this.props;
        let {ctx, setProperty,sealImagefileid} = odocSignApprovalStore;
        let _that = this;
        let saveCheck = true;
        alert(getLabel('521675', '当前签批文件未保存，是否要离开？'),
            <AgreeItem data-seed="logId"
                 className={"wea-sign-approval-savetip"}
                 defaultChecked={true}
                 onChange={e => {
                    saveCheck = e.target.checked;
                 }}>
                <span className={"save-sign-file-span"}>{getLabel('521676', '保存当前签批文件')}</span>
            </AgreeItem>, [
            {
                text: getLabel('31129', '取消'), onPress: () => {
                }
            },
            {
                text: getLabel('826', '确定'), onPress: () => {
                    if (saveCheck == true) {
                        ctx.SimulateClickBtn("wsSaveBtn");
                        setProperty({isSave: true});
                        let timer = setInterval(function () {
                            if (_that.props.odocSignApprovalStore.isSave == false) {
                                clearInterval(timer);
                                callback();
                            }
                        }, 500);
                    } else {
                        callback();
                    }
                }
            },
        ])
    }

    doRightMenuClick=(key)=>{
      let {history, odocSignApprovalStore} = this.props;
      let {btns, ctx,sealImagefileid,qpSelected,setProperty} = odocSignApprovalStore;
      let lastQpSelected = qpSelected;
      if(key=="download"){
        let url = "/weaver/weaver.file.FileDownload?fileid="+sealImagefileid+"&download=1";
        Tools.getWeaverFile(url);
      }else if (key == "more") {
        this.showActionSheet();
      } else if (key == "submit") {
        ctx.CloseWrite();
        if (ctx.CheckoutHasUnsaveData()) {
          ctx.SimulateClickBtn("wsSaveBtn");
          setTimeout(function () {
            WfForm.doRightBtnEvent("BTN_SUBBACKNAME");
            WfForm.doRightBtnEvent("BTN_SUBMIT");
            history.go(-1);
          }, 1000)
        } else {
          WfForm.doRightBtnEvent("BTN_SUBBACKNAME");
          WfForm.doRightBtnEvent("BTN_SUBMIT");
          history.go(-1);
        }

      } else if (key == "reject") {
        ctx.CloseWrite();
        if (ctx.CheckoutHasUnsaveData()) {
          ctx.SimulateClickBtn("wsSaveBtn");
          setTimeout(function () {
            WfForm.doRightBtnEvent("BTN_REJECTNAME");
            history.go(-1);
          }, 1000)
        } else {
          WfForm.doRightBtnEvent("BTN_REJECTNAME");
          history.go(-1);
        }
      }else {
        ctx.SimulateClickBtn(key)
        if(key=="wsWriteBtn"){
          setProperty({qpSelected:true});
        }else if(key=="wsSaveBtn"){
          if(lastQpSelected==true){
            setTimeout(function () {
              ctx.SimulateClickBtn("wsWriteBtn");//默认签批
              setProperty({qpSelected:true})
            },500)
          }
        }
      }

      if(key==="wsValidBtn"){
        let timer = setInterval(function () {
          if(jQuery(".ws-valid-scroll>div").length>0){
            clearInterval(timer);
            initSignApprovalTouchMove(jQuery(".ws-valid-scroll>div")[0]);
            signapprovalMoveForIos(jQuery(".ws-valid-view .ws-valid-opt .ws-icon-filter")[0]);
          }
        },100);
      }else if(key==="wsThumbBtn"){
        let timer = setInterval(function () {
          if(jQuery(".ws-thumb-scroll>div").length>0){
            clearInterval(timer);
            initSignApprovalTouchMove(jQuery(".ws-thumb-scroll>div")[0]);
          }
        },100);
      }
    }

    getBottomButtons = () => {
        let {history, odocSignApprovalStore} = this.props;
        let {btns, ctx} = odocSignApprovalStore;
        let btnLen = toJS(btns).length;
        return <Flex className={"wea-mobile-haoqian-button1"}>
            {
                toJS(btns).map((item, index) => {
                    if (btnLen > 5 && index >= 4) {
                        return;
                    }
                    return <Flex.Item onClick={() => {
                        this.doRightMenuClick(item.key)
                    }}><i className={`${item.icon} disabledfastclick`}></i><span className={"disabledfastclick"}>{item.name}</span></Flex.Item>
                })
            }
            {btnLen > 5 && <Flex.Item onClick={() => {this.showActionSheet();}}><i className={"icon-haoqian-more"}/><span>{getLabel(17499, '更多')}</span></Flex.Item>}
        </Flex>
    };

    getTopHeaderComp=()=>{
        let {odocSignApprovalStore,history} = this.props;
        let {btns, isShowQP, setProperty, layout, histroyDocs, sealDocs, sequenceId, sealName, ctx,showHeader,qpSelected} = odocSignApprovalStore;
        let histroyDocsLen = toJS(histroyDocs).length;
        let sealDocsLen = toJS(sealDocs).length;
        return <div className={"wea-haoqian-header"}>
            <div className={"haoqian-top-left"} onClick={(e) => {
                e.preventDefault()
            }}>
                <div className={"title"} onClick={(e) => {
                    e.preventDefault();
                    if(sealDocsLen>1){
                        setProperty({isShowQP: !isShowQP})
                    }
                }}>
                    <span style={{maxWidth:`${histroyDocsLen<=0?(winWidth-75):190}px`}}>{sealName.replace(".pdf", "")}</span>
                    {sealDocsLen>1 && <i className={`icon-haoqian-${isShowQP ? "up" : "down"}`}/>}
                </div>
                {isShowQP && <div className={"haoqian-top-left-menu"}>
                    <ul>
                        {
                            toJS(sealDocs).map(item => {
                                let filename = item.imagefilename.replace(".pdf", "");
                                return <li
                                    className={sequenceId == item.sequenceId ? "wea-haoqian-qp-select" : ""}
                                    onClick={() => {
                                        if (sequenceId != item.sequenceId) {
                                            let lastQpSelected = qpSelected;
                                            let changeQianFunc = () => {
                                                jQuery('#ctx').empty();
                                                setProperty({
                                                    sequenceId: item.sequenceId,
                                                    isShowQP: false,
                                                    sealName: item.imagefilename,
                                                    sealid: item.id,
                                                    sealImagefileid: item.encodeimagefileid
                                                });
                                                this.loadHaoQianPage();
                                            }
                                            ctx.CloseWrite();
                                            if (ctx.CheckoutHasUnsaveData()) {
                                                setProperty({isShowQP: false});
                                                this.doIsSaveTip(changeQianFunc);
                                            } else {
                                                changeQianFunc();
                                            }
                                            if(lastQpSelected==true){
                                              ctx.SimulateClickBtn("wsWriteBtn");//默认签批
                                              setProperty({qpSelected:true});
                                            }
                                        } else {
                                            setProperty({isShowQP: false});
                                        }
                                    }}>{filename}</li>
                            })
                        }
                    </ul>
                </div>}
            </div>
            {histroyDocsLen> 0 && <div className={"haoqian-top-right"} onClick={() => {
                let lastQpSelected = qpSelected;
                let goHistory = () => {
                    if(lastQpSelected==true){
                      ctx.SimulateClickBtn("wsWriteBtn");//默认签批
                      setProperty({qpSelected:true});
                    }
                    setProperty({isViewHistory: false, isShowQP: false});
                    history.push(layout.path);
                }
                ctx.CloseWrite();
                if (ctx.CheckoutHasUnsaveData()) {
                    this.doIsSaveTip(goHistory);
                } else {
                  goHistory();
                }
            }}><span>{getLabel('511897', '历史版本')}</span></div>}
        </div>
    }

    formOpenHrmCard=(checkOutUserid)=>{
        let url = `/spa/hrm/static4mobile/index.html#/resourceInfo/${checkOutUserid}`;
        CommonUtil.showHoverWindow(url,"/req/odocComs");
    }

    render() {
        let {odocSignApprovalStore} = this.props;
        let {btns, isShowQP, setProperty, layout, histroyDocs, sealDocs, sequenceId, sealName, ctx,showHeader,checkOutUsername,checkOut,checkOutUserid} = odocSignApprovalStore;

        let ctxHeight = 0;
        if(showHeader){ctxHeight+=44};
        if(toJS(btns).length > 0){ctxHeight+=50};
        let checkOutTip = "";
        if(checkOut=="0"){
            ctxHeight+=40;
            checkOutTip = getLabel(521962,"提示：当前文件正在由${user}签批中，您可以稍后再签批").replace("${user}",checkOutUsername);
        }
        return (
            <div style={{width: "100%", height: "100%"}} className={"wea-haoqian-box"}>
                {checkOut=="0" && <div className={"wea-mobile-hqoqian-checkout"}><div>{getLabel('523375','当前文件正在由')}<span style={{color:"rgb(16, 142, 233)"}} onClick={()=>{this.formOpenHrmCard(checkOutUserid)}}>{checkOutUsername}</span>{getLabel('523376','签批中，您可以稍后再签批')}</div></div>}
                {showHeader && this.getTopHeaderComp()}
                <div id="ctx"
                     style={{width: "100%", height: `calc(100% - ${ctxHeight}px)`}}></div>
                {toJS(btns).length > 0 && this.getBottomButtons()}

                <div id='haoqian1'>
                    <div>{getLabel('34130', '流程表单')}</div>
                </div>

                <Route
                    key={layout.id}
                    path={layout.path}
                    render={() => (
                        <RouteLayout>
                            <div
                                key="wmPoutePageDemo"
                                className="wm-route-layout wm-demo-route-layout-page"
                            >
                                <DocumentHistoryVersion/>
                            </div>
                        </RouteLayout>
                    )}
                />
            </div>
        );
    }
}

export default Index;